import createMatcher from './create-matcher'
import HashHistory from './history/hash'
import BrowserHistory from './history/history'
import install from './install'

class VueRouter {
  constructor(options) {
    // 1. match通过路由来匹配组件
    // 2. addRoutes 动态添加路由
    this.matcher = createMatcher(options.routes || [])

    // mode判断
    options.mode = options.mode || 'hash' // 默认为hash
    switch (options.mode) {
      case 'hash':
        this.history = new HashHistory(this)
        break

      case 'history':
        this.history = new BrowserHistory(this)
        break
    }
  }
  push(to) {
    this.history.push(to) // 跳转路由
  }
  go() {}
  match(location) {
    return this.matcher.match(location)
  }
  // 初始化操作
  init(app) {
    // 监听hash值变化 默认跳转到对应的路径中
    const history = this.history

    const setupHashListener = () => {
      history.setupListener() // 监听路由变化  hashchange
    }

    // 跳转操作
    history.transitionTo(history.getCurrentLocation(), setupHashListener)

    history.listen(route => {
      app._route = route
      console.log(app._route, '*******')
    })
  }
}

VueRouter.install = install

// 默认导出的是一个类，通过new Router()进行使用
export default VueRouter
